package com.dpiinc.TechPage.widget

import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import com.dpiinc.TechPage.R
import com.dpiinc.TechPage.utils.AppUtil

/**
 * 橡皮擦选择器
 * Created by X on 2018/7/7.
 */
class EraserPicker : LinearLayout, View.OnClickListener {
    companion object {
        private var ITEM_MARGIN: Int = AppUtil.dp2px(35f).toInt()//间距35dp
    }

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)

    private val sizeList = ArrayList<Float>()
    private var selectedEraserIndex = 1//默认是中型尺寸

    var onEraserPicked: ((size: Float) -> Unit)? = null

    fun getSelectEraserRadius(): Float {
        return if (selectedEraserIndex >= 0 && selectedEraserIndex < sizeList.size) {
            sizeList[selectedEraserIndex] / 2//半径
        } else {
            0f
        }
    }

    init {
        orientation = HORIZONTAL
        gravity = Gravity.CENTER
//        setBackgroundColor(Color.WHITE)
        sizeList.add(12f)
        sizeList.add(24f)
        sizeList.add(36f)
        sizeList.forEach {
            addItem(it)
        }
        select(selectedEraserIndex)
    }

    private fun addItem(size: Float) {
        val itemView = LayoutInflater.from(context).inflate(R.layout.eraser_item_layout, this, false)
        val sizeInPixels = AppUtil.dp2px(size)
        val layoutParams = LayoutParams(sizeInPixels.toInt(), sizeInPixels.toInt())
        if (childCount != 0) {
            layoutParams.leftMargin = ITEM_MARGIN
        }
        val position = childCount
        itemView.setTag(R.layout.eraser_item_layout, position)
        itemView.setOnClickListener(this)
        addView(itemView, layoutParams)
    }

    override fun onClick(v: View?) {
        v?.let {
            val position = it.getTag(R.layout.eraser_item_layout) as Int
            select(position)
        }
    }

    public fun select(index: Int) {
        if (index < 0 || index >= childCount) {
            return
        }
        selectedEraserIndex = index
        val itemView = getChildAt(index)
        resetState()
//        val padding = Math.round(AppUtil.dp2px(3f))
//        itemView.setPadding(padding, padding, padding, padding)
        itemView.setBackgroundResource(R.drawable.eraser_item_selected_border)
        itemView.isSelected = true
        onEraserPicked?.invoke(getSelectEraserRadius())
    }

    private fun resetState() {
        for (index in 0 until childCount) {
            val itemView = getChildAt(index)
//            itemView.setPadding(0, 0, 0, 0)
            itemView.background = null
            itemView.isSelected = false
        }
    }
}